package com.miguo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.miguo.ui.R;

import java.util.ArrayList;
import java.util.List;

/**
 * File Names: AutoCompleteAdapter
 * Describe:
 * User: LinXiaoZhi(87100854@qq.com)
 * Date: 2015-08-09
 * Time: 17:19
 */
public class AutoCompleteAdapter extends BaseAdapter implements Filterable {

    private List<String> mList;
    private Context mContext;
    private AutoCompleteFilter mFilter;

    public AutoCompleteAdapter(Context context) {
        mContext = context;
        mList = new ArrayList<String>();
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList == null ? null : mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater layoutInflator = LayoutInflater.from(mContext);
            convertView = layoutInflator.inflate(R.layout.dropdown_item, parent, false);
            holder = new ViewHolder();
            holder.txt = (TextView) convertView.findViewById(R.id.tv_text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.txt.setText(mList.get(position));
        return convertView;
    }

    static class ViewHolder {
        private TextView txt;
    }

    @Override
    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new AutoCompleteFilter();
        }
        return mFilter;
    }


    public void add(String string) {
        mList.add(string);
    }

    public void clear() {
        mList.clear();
    }

    private class AutoCompleteFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (mList == null) {
                mList = new ArrayList<String>();
            }
            results.values = mList;
            results.count = mList.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

